package com.aplikata.evok.ui;

import java.util.List;
import java.util.Locale;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;

import org.primefaces.event.SelectEvent;

import com.aplikata.bo.City;
import com.aplikata.bo.User;
import com.aplikata.constants.ConstantsMsg;
import com.aplikata.evok.bo.ContactPerson;
import com.aplikata.evok.bo.Patient;
import com.aplikata.evok.datamodel.ContactPersonDataModel;
import com.aplikata.evok.service.EvokPatientService;
import com.aplikata.ui.UIBean;
import com.aplikata.util.FacesUtil;
import com.aplikata.util.StringUtil;

/**
 * @ClassName: EvokPatientBean
 * @Description: TODO
 * @author Huyun
 * @date 17. 5. 2012. 09:10:03
 */
@ManagedBean(name = "evokPatientProfileBean")
@ViewScoped
public class EvokPatientProfileBean extends UIBean {
	private static final long serialVersionUID = 1L;

	private Patient patient;

	@ManagedProperty(value = "#{evokPatientService}")
	private EvokPatientService patientService;

	private Long birthRegionId;
	private Long birthCityId;
	private String birthPostcode;
	private List<City> birthCityList;

	private Long liveRegionId;
	private Long liveCityId;
	private String livePostcode;
	private List<City> liveCityList;
	private String userName;

	private ContactPerson contactPerson;
	private ContactPersonDataModel contactPersonModel;
	private Long contactRegionId;
	private Long contactCityId;
	private String contactPostcode;
	private List<City> contactCityList;

	private int tabIndex;

	@PostConstruct
	public void init() {
		contactPerson = new ContactPerson();
	}

	@SuppressWarnings({ "rawtypes" })
	public void getPatientAction() {
		patient = (Patient) patientService.findSingleByNamedQuery(Patient.QY_FIND_BY_USER, new Object[] { FacesUtil.getUserFromSession().getId() });

		String sqlcity = "select {c1.*}, {c2.*} from evk_patient p, _city c1, _city c2 where c1.id=p.birthplace and c2.id=p.city_id and p.id = "
				+ patient.getId();
		List listcity = patientService.getSqlQuery(sqlcity).addEntity("c1", City.class).addEntity("c2", City.class)
				.list();
		Object[] objcity = (Object[]) listcity.get(0);

		City cityBirth = (City) objcity[0];
		birthRegionId = cityBirth == null ? null : cityBirth.getRegion().getId();
		birthRegionChange();
		birthCityId = cityBirth == null ? null : cityBirth.getId();
		birthPostcode = cityBirth == null ? null : cityBirth.getPostCode();

		City cityLive = (City) objcity[1];
		liveRegionId = cityLive == null ? null : cityLive.getRegion().getId();
		liveRegionChange();
		liveCityId = cityLive == null ? null : cityLive.getId();
		livePostcode = cityLive == null ? null : cityLive.getPostCode();

		contactPerson = new ContactPerson();
		contactPersonModel = null;
		tabIndex = 0;
	}


	public String submitPatient() {
		try {
			//patient.setDomain(FacesUtil.getDomainFromSession());
			Long tempId = patient.getId();

			if (birthCityId != null) {
				patient.setBirthplace((City) patientService.get(City.class, birthCityId));
			}
			if (liveCityId != null) {
				//patient.setCity((City) patientService.get(City.class, liveCityId));
			}

			userName = this.getUserName();
			patient = patientService.updatePatient(true, patient, null, userName, null).getPatient();
			FacesUtil.addInfoMessage(ConstantsMsg.INFO_SUCCESS,
					new Object[] { patient.getSurname() + " " + patient.getName() });

			if (FacesUtil.isKeyNull(tempId)) {
				contactPerson = new ContactPerson();
				contactPersonModel = null; 
			}

		} catch (Exception e) {
			FacesUtil.addActionListenerException(e, log);
		}
		return "/pages/aplikata/evok/patient/profile.xhtml";
	}

	@SuppressWarnings("unchecked")
	public void birthRegionChange() {
		if (birthRegionId == null)
			birthCityList = null;
		else
			birthCityList = (List<City>) patientService.findByNamedQuery(City.QY_FIND_BY_REGION,
					new Object[] { birthRegionId });

		birthPostcode = null;
	}

	public void birthCityChange() {
		City city = (City) patientService.get(City.class, birthCityId);
		birthPostcode = city.getPostCode();
	}

	@SuppressWarnings("unchecked")
	public void liveRegionChange() {
		if (liveRegionId == null)
			liveCityList = null;
		else
			liveCityList = (List<City>) patientService.findByNamedQuery(City.QY_FIND_BY_REGION,
					new Object[] { liveRegionId });

		livePostcode = null;
	}

	public void liveCityChange() {
		City city = (City) patientService.get(City.class, liveCityId);
		livePostcode = city.getPostCode();
	}

	@SuppressWarnings("unchecked")
	public void contactRegionChange() {
		if (contactRegionId == null)
			contactCityList = null;
		else
			contactCityList = (List<City>) patientService.findByNamedQuery(City.QY_FIND_BY_REGION,
					new Object[] { contactRegionId });

		contactPostcode = null;
	}

	public void contactCityChange() {
		City city = (City) patientService.get(City.class, contactCityId);
		contactPostcode = city.getPostCode();
	}

	public void submitContactPerson() {
		try {
			if (patient == null || FacesUtil.isKeyNull(patient.getId()) || contactPerson == null)
				return;
			if (contactCityId != null) {
				contactPerson.setCity((City) patientService.get(City.class, contactCityId));
			}
			//contactPerson.setPatient(patient);
			patientService.merge(contactPerson);
			contactPerson = new ContactPerson();
			contactRegionId = null;
			contactCityId = null;
			contactPostcode = null;
			contactPersonModel = null;
			contactPersonModel = this.getContactPersonModel();
		} catch (Exception e) {
			FacesUtil.addActionListenerException(e, log);
		}
	}
	
	public void resetContactPerson(){
		contactPerson = new ContactPerson();
		contactRegionId = null;
		contactCityId = null;
		contactPostcode = null;
		FacesUtil.unselectTableRows("wdgContactList");
	}

	public void selectContactPerson(SelectEvent event) {
		contactPerson = (ContactPerson) event.getObject();
		City city = contactPerson.getCity();
		contactRegionId = city == null ? null : city.getRegion().getId();
		contactRegionChange();
		contactCityId = city == null ? null : city.getId();
		contactPostcode = city == null ? null : city.getPostCode();
	}

	public void deleteContactPerson() {
		try {
			patientService.delete(contactPerson);
			contactPerson = new ContactPerson();
			contactRegionId = null;
			contactCityId = null;
			contactPostcode = null;
			contactPersonModel = null;
			contactPersonModel = this.getContactPersonModel();
		} catch (Exception e) {
			FacesUtil.addActionListenerException(e, log);
		}
	}

	public String getUserName() {
		if (patient == null)
			return null;

		if (!FacesUtil.isKeyNull(patient.getId())) {
			User user = null;
			user = (User) patientService.findSingleByNamedQuery(Patient.QY_FIND_USER, new Object[] { patient.getId() });
			userName = user == null ? null : user.getUserName();
			return userName;
		}

		String name = patient.getName();
		if (!StringUtil.isStrEmpty(name)) {
			name = name.substring(0, 1).toLowerCase();
		} else {
			name = "";
		}
		String surname = patient.getSurname();
		if (!StringUtil.isStrEmpty(surname)) {
			surname = surname.toLowerCase(Locale.ENGLISH);
			if (surname.length() > 11) {
				surname = surname.substring(0, 10);
			}
		} else {
			surname = "";
		}

		userName = name + surname;
		return userName;
	}

	public EvokPatientService getPatientService() {
		return patientService;
	}

	public void setPatientService(EvokPatientService patientService) {
		this.patientService = patientService;
	}

	public Patient getPatient() {
		if(patient == null)
			getPatientAction();
		return patient;
	}

	public void setPatient(Patient patient) {
		this.patient = patient;
	}

	public Long getBirthRegionId() {
		return birthRegionId;
	}

	public void setBirthRegionId(Long birthRegionId) {
		this.birthRegionId = birthRegionId;
	}

	public Long getBirthCityId() {
		return birthCityId;
	}

	public void setBirthCityId(Long birthCityId) {
		this.birthCityId = birthCityId;
	}

	public String getBirthPostcode() {
		return birthPostcode;
	}

	public void setBirthPostcode(String birthPostcode) {
		this.birthPostcode = birthPostcode;
	}

	public List<City> getBirthCityList() {
		return birthCityList;
	}

	public void setBirthCityList(List<City> birthCityList) {
		this.birthCityList = birthCityList;
	}

	public Long getLiveRegionId() {
		return liveRegionId;
	}

	public void setLiveRegionId(Long liveRegionId) {
		this.liveRegionId = liveRegionId;
	}

	public Long getLiveCityId() {
		return liveCityId;
	}

	public void setLiveCityId(Long liveCityId) {
		this.liveCityId = liveCityId;
	}

	public String getLivePostcode() {
		return livePostcode;
	}

	public void setLivePostcode(String livePostcode) {
		this.livePostcode = livePostcode;
	}

	public List<City> getLiveCityList() {
		return liveCityList;
	}

	public void setLiveCityList(List<City> liveCityList) {
		this.liveCityList = liveCityList;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public ContactPerson getContactPerson() {
		return contactPerson;
	}

	public void setContactPerson(ContactPerson contactPerson) {
		this.contactPerson = contactPerson;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public ContactPersonDataModel getContactPersonModel() {
		if (patient == null || FacesUtil.isKeyNull(patient.getId()))
			return null;

		if (contactPersonModel == null) {
			List list = patientService.findByNamedQuery(ContactPerson.QY_FIND_BY_PATIENT,
					new Object[] { patient.getId() });
			contactPersonModel = new ContactPersonDataModel(patientService, list);
		}
		return contactPersonModel;
	}

	public void setContactPersonModel(ContactPersonDataModel contactPersonModel) {
		this.contactPersonModel = contactPersonModel;
	}

	public Long getContactRegionId() {
		return contactRegionId;
	}

	public void setContactRegionId(Long contactRegionId) {
		this.contactRegionId = contactRegionId;
	}

	public Long getContactCityId() {
		return contactCityId;
	}

	public void setContactCityId(Long contactCityId) {
		this.contactCityId = contactCityId;
	}

	public String getContactPostcode() {
		return contactPostcode;
	}

	public void setContactPostcode(String contactPostcode) {
		this.contactPostcode = contactPostcode;
	}

	public List<City> getContactCityList() {
		return contactCityList;
	}

	public void setContactCityList(List<City> contactCityList) {
		this.contactCityList = contactCityList;
	}

	public int getTabIndex() {
		return tabIndex;
	}

	public void setTabIndex(int tabIndex) {
		this.tabIndex = tabIndex;
	}

}
